package com.SmartCare.schedule;

import com.SmartCare.utils.DataBackupUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Component
@EnableScheduling
public class DbHistoryTask {

    /**
     * 备份文件名称
     */
    @Value("${backup.datasource.table}")
    private String table;


    /**
     * 删除多少天前数据库备份
     */
    @Value("${backup.deleteDay}")
    private String deleteDay;

    /**
     * Linux备份路径
     */
    @Value("${backup.backupLPath}")
    private String backupLPath;
    @Value("${backup.scriptPath}")
    private String scriptPath;

    //@Scheduled(cron = "0 0 * * * *") //每小时
    @Scheduled(cron = "0 0 */3 * * ?") //每三小时执行一次
    private void dbBackup() {

        log.info("系统开启定时任务数据库振动器表备份");

        // 当前时间 年月日格式
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); // Format: yyyyMMddHHmm
        String formattedTime = currentTime.format(formatter);

        // linux的路径是/ ，filename是文件的名字
        String pathName= backupLPath + "/";
        String fileName = table +"_"+ formattedTime + ".sql";
        File file = new File(pathName, fileName);
        // 调用数据库备份方法
        DataBackupUtil.backup(file, scriptPath);

        log.info("系统结束定时任务数据库备份");
    }

    // 定时任务每天凌晨2点执行删除备份文件
    @Scheduled(cron = "0 0 2 * * *")
    private void deleteOldBackupFiles() {
        log.info("系统开启定时任务删除旧的数据库备份文件");

        LocalDate sevenDaysAgo = LocalDate.now().minusDays(Long.parseLong(deleteDay));
        File backupDir = new File(backupLPath);

        if (backupDir.exists() && backupDir.isDirectory()) {
            File[] files = backupDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    LocalDate fileCreationDate = LocalDate.ofEpochDay(file.lastModified() / (24 * 60 * 60 * 1000));
                    // 删除创建时间在七天前的文件
                    if (fileCreationDate.isBefore(sevenDaysAgo)) {
                        boolean res = file.delete();
                        if (res)
                            log.info("成功删除备份文件: {}", file.getName());
                        log.info("删除备份文件失败: {}", file.getName());
                    }
                }
            }
        } else {
            log.warn("备份目录不存在或者不是一个目录");
        }
        log.info("系统结束定时任务删除旧的数据库备份文件");
    }

}
